/**
 * @description 指令下达
 * @author LT 
 * 入参
 * 
  type：1-指令新增   2-簿记新增    3-详情  4-交收  11-组合试算
  info：type=3 || 4时，需回填字段
  onRef：组件指针
  getInfo：通过onRef，调用getInfo方法，获取各字段的值，在getInfo中完成校验，若校验不通过，返回undefined
  reset：通过onRef，调用reset方法，清空页面字段
  productOnChange：产品变更事件，输出当前产品ID，若无则为undefined；
  portfolioOnChange：组合变更事件，输出当前组合ID，若无则为undefined；
  tradingcodeOnChange：证券代码变更事件，输出当前证券id（证券唯一标识符ID）、tradingCode（证券代码）、securityType（证券类别），若无则为undefined。
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { codeType, FormGroup, DATA_ENTRY } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { calculateFee } from '../../../../utils/commonFunc';
import investmentType from '../../../../utils/enumeratedValues/investmentType';

class OrderFormC extends PureComponent {
  static defaultProps = {
    type: 1,
    info: undefined,
    onRef: () => {},
    portfolioOnChange: () => {},
    productOnChange: () => {},
    tradingcodeOnChange: () => {},
  };
  state = {
    info: undefined, //详情
    type: undefined, //当前指令的类型
    SecuritiesCode: undefined, //证券代码val值
    directionType: '1',
    feeData: {
      //费用自动计算条件
      productId: undefined,
      portfolioid: undefined,
      tradingCode: undefined,
      exchangecode: undefined,
      sectype: 'ww',
      price: undefined,
    },
    isRoll: false,
    price: undefined,
    total: undefined,
    amount: undefined,
  };
  componentDidMount() {
    this.props.onRef(this);
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    // 试算隐藏价格等参数
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.props;
    if (this.state.directionType === '2' && nextProps?.investmentType !== getFieldValue('investmentType')) {
      if (nextProps.info) return; //详情不进入
      setFieldsValue({
        investmentType: nextProps.investmentType,
      });
    }
  }
  //费用自动计算
  changeFeeCalculate = (type, data) => {
    const {
      form: { setFieldsValue },
    } = this.props;
    if (this.props.type == '3' || this.props.type == '4') {
      return; //详情不计算
    }
    if (data == undefined) {
      setFieldsValue({ fee: undefined });
      this.changeFee();
      if (type == 'tradingCode') {
        this.setState({ feeData: { ...this.state.feeData, tradingCode: undefined } });
      } else if (type == 'productId') {
        this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
      } else {
        this.setState({ feeData: { ...this.state.feeData, [type]: undefined } });
      }
    } else {
      if (type == 'tradingCode') {
        this.setState({ feeData: { ...this.state.feeData, tradingCode: data?.tradingCode } }, () => {
          let fee = calculateFee(this.state.feeData);
          fee.then((r) => {
            setFieldsValue(
              { fee: r },
              this.setState({ fee: r }, () => this.changeFee(r)),
            );
          });
        });
      } else {
        this.setState({ feeData: { ...this.state.feeData, [type]: data } }, () => {
          let fee = calculateFee(this.state.feeData);
          fee.then((r) => {
            setFieldsValue(
              { fee: r },
              this.setState({ fee: r }, () => this.changeFee(r)),
            );
          });
        });
      }
    }
  };
  //费用修改
  changeFee = (e) => {
    this.setState({
      fee: e || 0,
    });
  };
  //组合改变
  groupOnChange = (value) => {
    //抛出组合id
    this.props.portfolioOnChange(value);
    this.changeFeeCalculate('portfolioid', value?.key);
  };
  // 产品变化 清除组合
  productOnChange = (value) => {
    this.setState(
      {
        feeData: {
          ...this.state.feeData,
          portfolioid: undefined,
        },
      },
      () => {
        this.changeFeeCalculate('productId', value?.key);
      },
    );
    // 向外抛出产品code
    this.props.productOnChange(value ? value.info.portfolioCode : undefined);
  };
  //证券代码切换
  securitiesCodeChange = (value) => {
    const { info } = this.props;
    if (info) return; //详情时不进入判断
    this.changeFeeCalculate('tradingCode', value ? value : undefined);
    this.setState({
      SecuritiesCode: value,
      feeData: {
        ...this.state.feeData,
        exchangecode: value?.exchangeCode,
        tradingCode: value?.tradingCode,
      },
    });
    this.props.tradingcodeOnChange(value);
  };
  // 交易方向变更 投资类型变更买入时默认为FVTPL，卖出时，根据标的，自动回填。
  changeDirect = (e) => {
    const {
      form: { setFieldsValue },
    } = this.props;
    const { info } = this.props;
    this.setState({ directionType: e?.value });
    if (info) return; //详情不进入
    this.changeFeeCalculate('orderside', e?.value);
    if (e?.title == '卖出') {
      setFieldsValue({
        investmentType: this.props.investmentType,
      });
    }
  };
  //重置页面数据 取消
  reset = () => {
    const { form } = this.props;
    this.props.portfolioOnChange(undefined);
    this.props.tradingcodeOnChange(undefined); //重置组合id和证券代码
    this.setState({
      info: undefined, //详情
      type: undefined, //当前指令的类型
      SecuritiesCode: undefined, //证券代码val值
      directionType: '1',
      feeData: {
        //费用自动计算条件
        productId: undefined,
        portfolioid: undefined,
        tradingCode: undefined,
        exchangecode: undefined,
        sectype: 'wwtz',
        orderside: undefined,
        price: undefined,
      },
      price: undefined,
      amount: undefined,
      total: undefined,
      isRoll: false,
    });
    form.resetFields();
  };
  //修改交易总额 数量 金额 = 价格 * 数量 后台根据【委托价格】和【委托数量】自动算出费用
  changeNum = (e, type) => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.props;
    let data = getFieldValue(type);
    this.setState(
      {
        [type]: e || undefined,
      },
      () => {
        if (type === 'total') {
          if (this.state.amount) {
            let price = parseFloat(parseFloat(e || 0) / parseFloat(this.state.amount));
            this.setState({
              price,
            });
            setFieldsValue({
              price,
            });
          }
          this.changeFeeCalculate('price', e || 0);
          return;
        }
        if (this.state.price && this.state.amount) {
          let total = parseFloat(this.state.price * this.state.amount); // 金额 = 委托价格 * 委托数量
          this.changeFeeCalculate('price', total);
          setFieldsValue({
            parValueTotal: total,
          });
        } else {
          setFieldsValue({ parValueTotal: undefined });
        }
      },
    );
  };
  // 获取表单数据 并校验
  getInfo = () => {
    const {
      form: { validateFields },
      user: { currentUser },
      money = {},
      position = {},
      dateInterval = {},
    } = this.props;
    let formData = undefined;
    validateFields((error, values) => {
      if (!error) {
        if (this.state.loadingFee) {
          message.warning('费用还在计算中,请稍后重试!');
          return;
        }
        // （4）试算和确定校验
        // 【交易方向】为“买入”时，需要验资，【交易总额】需小于T+0可用，若大于，则提示“【交易总额】不能大于T+0可用”；
        if (values.direction == '1' && values.parValueTotal > (money?.t0 || 0)) {
          message.error('【交易总额】不能大于T+0可用！');
          return;
        }
        // 【交易方向】为“卖出”时，需要验券，【交易数量】需小于可用数量，若大于，则提示“【交易数量】不能大于可用数量”；
        if (values.direction == '2' && values.amount > (position?.available || 0)) {
          message.error('【交易数量】不能大于可用数量！');
          return;
        }

        formData = values;
        formData.userid = currentUser.userId;
        formData.username = currentUser.name;
        formData.tradingcode = this.state.SecuritiesCode.tradingCode;
        formData.exchangeCode = this.state.SecuritiesCode.exchangeCode;
        formData.secuabbr = this.state.SecuritiesCode.secuabbr;
        formData.fee = 0; // 费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑
        delete formData.zqdm;
      }
    });
    return formData;
  };

  render() {
    const { isRoll } = this.state;
    const { type, info } = this.props;
    let disabled;
    if ([1, 2, 3, 4, 11].includes(type)) {
      disabled = false;
    } else {
      disabled = true;
    }
    const formGroupProps = {
      form: this.props.form,
      autoLayout: false,
      dataSource: [
        {
          title: ['产品', '组合'],
          dataIndex: ['productid', 'portfolioid'],
          type: DATA_ENTRY.PRODUCTGROUPSEP,
          initialValue: info ? [info.productid, info.portfolioid] : undefined,
          rules: [[{ required: true, message: '请选择产品!' }], [{ required: true, message: '请选择组合!' }]],
          groupOnChange: (e) => this.groupOnChange(e),
          productOnChange: (e) => this.productOnChange(e),
          span: 16,
          controlLabelSpan: 6,
          exist: 1,
          allowClear: false,
          multipleGroup: false,
          authority: 'write',
          disabled: disabled,
          tradeModel: type == 1 || type == 2 ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined, //不包含估值解析和估值对接的产品
        },
        {
          dataIndex: 'zqdm',
          title: '证券代码',
          type: DATA_ENTRY.SECURITIESCODE,
          initialValue: info ? `${info.exchangeCode}-${info.tradingcode}` : undefined,
          onChange: (e) => this.securitiesCodeChange(e),
          codeType: codeType.outsourcing,
          rules: [{ required: true, message: '请选择证券代码!' }],
          disabled: disabled,
          queryItems: { time: moment(new Date()).format('YYYY-MM-DD') },
          span: 8,
          controlLabelSpan: 6,
        },
        {
          dataIndex: 'direction',
          title: '交易方向',
          type: DATA_ENTRY.TRADINGDIRECT,
          businessType: '21',
          initialValue: info ? info.direction : '1',
          disabled: disabled,
          allowClear: false,
          rules: [{ required: true, message: '请选择交易方向!' }],
          onChange: this.changeDirect,
          appType: info ? '2' : undefined,
          span: 8,
          controlLabelSpan: 6,
        },
        {
          dataIndex: 'price',
          title: '交易价格',
          type: DATA_ENTRY.INPUTNUMBER,
          unit: '元',
          initialValue: info ? info.price : undefined,
          disabled: disabled,
          splitStyle: true,
          precision: 2,
          rules: [{ required: true, message: '请输入交易价格!' }],
          min: 0.01,
          onChange: (e) => this.changeNum(e, 'price'),
          span: 8,
          controlLabelSpan: 6,
        },
        {
          dataIndex: 'amount',
          title: '交易数量',
          type: DATA_ENTRY.INPUTNUMBER,
          unit: '份',
          initialValue: info ? info.amount : undefined,
          disabled: disabled,
          splitStyle: true,
          precision: 0,
          rules: [{ required: true, message: '请输入交易数量!' }],
          min: 1,
          onChange: (e) => this.changeNum(e, 'amount'),
          span: 8,
          controlLabelSpan: 6,
        },
        {
          dataIndex: 'parValueTotal',
          title: '交易总额',
          type: DATA_ENTRY.INPUTNUMBER,
          unit: '元',
          initialValue: info ? info.parValueTotal : undefined,
          disabled: disabled,
          splitStyle: true,
          precision: 2,
          rules: [{ required: true, message: '请输入交易总额!' }],
          min: 0.01,
          onChange: (e) => this.changeNum(e, 'total'),
          span: 8,
          controlLabelSpan: 6,
        },
        // {
        //   hide: isRoll,
        //   dataIndex: 'fee',
        //   title: '费用',
        //   type: DATA_ENTRY.INPUTNUMBER,
        //   unit: '元',
        //   initialValue: info ? info.fee : undefined,
        //   disabled: disabled,
        //   splitStyle: true,
        //   precision: 2,
        //   min: 0,
        //   onChange: this.changeFee,
        //   span: 8,
        // controlLabelSpan:6,
        // },
        {
          dataIndex: 'investmentType',
          title: '投资类型',
          type: DATA_ENTRY.SELECT,
          initialValue: info ? info.investmentType : 'FVTPL',
          disabled: disabled == false ? (this.state.directionType == '2' ? true : false) : disabled,
          dataSource: investmentType || [],
          span: 8,
          controlLabelSpan: 6,
        },
        {
          lineOne: true,
          dataIndex: 'remark',
          type: DATA_ENTRY.INPUT,
          title: '备注',
          initialValue: info ? info.remark : undefined,
          placeholder: '请输入',
          rules: [{ max: 100, message: '不能超过100个字' }],
          showTextArea: true,
          disabled: disabled,
          max: 100,
          autosize: { minRows: 2, maxRows: 2 },
          span: 24,
          controlLabelSpan: 2,
        },
      ],
    };
    return <FormGroup {...formGroupProps} />;
  }
}
export default connect(({ userM: user, loading }) => ({
  user,
  loading,
}))(Form.create()(OrderFormC));
